<template>
  <view>
    <u-navbar height="50" title="订单详情" title-size="36" title-color="#333"></u-navbar>
    <scroll-view v-if="orderInfo" :scroll-y="true">
      <view class="layoutView">
        <view class="orderStatus dis-flex flex-y-center">
          <text class="flex-1">{{ orderInfo.statusName }}</text>
          <text
            v-if="orderInfo.type === 10"
            style="font-weight: bold; font-size: 28rpx; margin-right: 20rpx"
            >外卖
          </text>
          <text
            v-if="orderInfo.reserveDate"
            style="color: #cb6501; font-weight: bold; font-size: 28rpx; margin-right: 20rpx"
            >预约</text
          >
          <view v-if="orderInfo.status === 0" style="font-size: 28rpx">
            <text style="margin-right: 10rpx">支付剩余时间</text>
            <u-count-down
              v-if="orderInfo.status === 0"
              :timestamp="payCountDownSeconds"
              :show-border="true"
              font-size="26"
              color="#ff0000"
              border-color="#bb0000"
            >
            </u-count-down>
          </view>
        </view>
        <view class="dis-flex flex-y-between" style="font-size: 28rpx; line-height: 50rpx">
          <view class="flex-1">
            <view
              v-if="orderInfo.deliveryType == 1 || orderInfo.deliveryType == 3"
              class="order-address"
            >
              {{ orderInfo.receiverAreaName }}&nbsp;&nbsp;{{ orderInfo.receiverDetailAddress }}
            </view>
            <view
              v-if="orderInfo.deliveryType == 1 || orderInfo.deliveryType == 3"
              class="order-contacts dis-flex flex-x-baseline"
            >
              <text>{{ orderInfo.receiverName }}&nbsp;&nbsp;{{ orderInfo.receiverMobile }}</text>
              <view
                style="color: #10a28f; font-size: 26rpx; margin-left: 30rpx"
                @click.stop.prevent="onCallPhone(orderInfo.riderStaff.contactMobile)"
              >
                联系TA
              </view>
            </view>
          </view>
        </view>
        <view v-if="orderInfo.deliveryType == 4">
          <view class="store-info dis-flex flex-y-between flex-y-center">
            <view class="store-left" style="flex: 1">
              <view>
                {{ orderInfo.shop.name }}
              </view>
              <view class="store-add"> 地址：{{ orderInfo.shop.fullAddress }}</view>
              <view class="store-add"> 电话：{{ orderInfo.shop.contactMobile }}</view>
            </view>
          </view>
          <view v-if="orderInfo.payStatus" class="dis-flex flex-y-between flex-y-center">
            <view class="order-code">
              <view v-if="orderInfo.refundStatus === 0 && orderInfo.status !== 30"
                >{{ formatCode(orderInfo.verifyCode) }}
              </view>
              <view v-else style="color: #999999; text-decoration: line-through"
                >{{ formatCode(orderInfo.verifyCode) }}
              </view>
            </view>
            <u-image
              v-if="orderInfo.refundStatus == 0"
              @click="toClerk"
              :src="orderInfo.qrcode"
              width="90rpx"
              height="90rpx"
            ></u-image>
          </view>
        </view>
      </view>
      <view class="layoutView">
        <view
          v-if="orderInfo.shop && orderInfo.shop.name"
          class="layoutText dis-flex flex-y-center"
        >
          <image
            v-if="orderInfo.shop.logo"
            :src="orderInfo.shop.logo"
            style="width: 40rpx; height: 40rpx"
          ></image>
          <text style="margin-left: 10rpx">{{ orderInfo.shop.name }}</text>
        </view>
        <text v-else class="layoutText"
          >{{ orderInfo.shop.categoryCode === 'food' ? '菜品信息' : '商品信息' }}
        </text>
        <view class="order-goods" v-for="(item2, index) in goodsList" :key="index">
          <u-image
            class="goods-img"
            border-radius="8"
            :src="item2.picUrl"
            width="160rpx"
            height="160rpx"
          ></u-image>
          <view class="orde-riget" style="flex: 1">
            <view class="goods-title">
              <text>{{ item2.spuName }}</text>
            </view>
            <view class="goods-speci dis-flex flex-x-baseline">
              <text v-if="item2.properties && item2.properties.length > 0"
                >{{ item2.properties[0].valueName }}
              </text>
              <text class="goodsNum" style="margin-left: 20rpx"
                >{{ item2.count }}{{ item2.unitValue > 1 ? 'x' + item2.unitValue : ''
                }}{{ item2.unitName || '' }}
              </text>
              <view class="flex-1"></view>
              <text class="goodsNum" v-if="item2.weight"
                >约{{ (item2.count * item2.weight * 1000).toFixed(0) }}克
              </text>
            </view>
            <view class="goods-price">
              <text>¥{{ (item2.price * 0.01).toFixed(2) }}</text>
              <text
                class="goods-refund"
                v-if="
                  item2.afterSaleStatus === 10 ||
                  item2.afterSaleStatus === 20 ||
                  item2.afterSaleStatus === 30
                "
              >
                退款进行中
              </text>
              <text class="goods-refund" v-else-if="item2.afterSaleStatus === 40">
                等待平台退款
              </text>
              <text class="goods-refund" v-else-if="item2.afterSaleStatus === 50"> 退款成功 </text>
              <text class="goods-refund" v-else> 已终止退款</text>
            </view>
          </view>
        </view>
        <view style="margin-top: 20rpx"></view>
        <u-line color="#E3E4E6"></u-line>
        <view class="moneyView dis-flex flex-y-center flex-y-between">
          <view class="moneyTitle">
            <view>合计</view>
          </view>
          <text style="color: #fa453c">¥{{ (priceTotal * 0.01).toFixed(2) }}</text>
        </view>
        <u-line
          color="#E3E4E6"
          v-if="orderInfo.deliveryType === 1 || orderInfo.deliveryType === 3"
        ></u-line>
        <view class="moneyView" v-if="orderInfo.deliveryType === 1 || orderInfo.deliveryType === 3">
          <view class="moneyTitle">
            <view>{{ orderInfo.deliveryType === 1 ? '运费' : '配送费' }}</view>
          </view>
          <view class="moneyText" v-if="Number(orderInfo.deliveryPrice) > 0"
            >¥{{ (orderInfo.deliveryPrice * 0.01).toFixed(2) }}
          </view>
          <view class="moneyText" v-else>{{ orderInfo.deliveryType === 1 ? '包邮' : '免费' }}</view>
        </view>
        <u-line color="#E3E4E6" v-if="orderInfo.deductPoint > 0"></u-line>
        <view class="moneyView" v-if="orderInfo.deductPoint > 0">
          <view class="moneyTitle">
            <view>积分</view>
          </view>
          <view class="moneyText" style="color: orangered"
            >{{ orderInfo.deductPoint }}积分抵¥{{ (orderInfo.pointPrice * 0.01).toFixed(2) }}
          </view>
        </view>
        <u-line color="#E3E4E6" v-if="orderInfo.deductCryptocurrency > 0"></u-line>
        <view class="moneyView" v-if="orderInfo.deductCryptocurrency > 0">
          <view class="moneyTitle">
            <view>收益豆</view>
          </view>
          <view class="moneyText" style="color: orangered"
            >{{ orderInfo.deductCryptocurrency }}个豆抵¥{{
              (orderInfo.cryptocurrencyPrice * 0.01).toFixed(2)
            }}
          </view>
        </view>
        <u-line color="#E3E4E6" v-if="orderInfo.vipPrice > 0"></u-line>
        <view class="moneyView" v-if="orderInfo.vipPrice > 0">
          <view class="moneyTitle">
            <view>会员价</view>
          </view>
          <view class="moneyText" style="color: orangered"
            >减免¥{{ (orderInfo.vipPrice * 0.01).toFixed(2) }}
          </view>
        </view>
        <u-line color="#E3E4E6" v-if="orderInfo.couponPrice > 0"></u-line>
        <view class="moneyView" v-if="orderInfo.couponPrice > 0">
          <view class="moneyTitle">
            <view>优惠券</view>
          </view>
          <view class="moneyText" style="color: orangered"
            >减免¥{{ (orderInfo.couponPrice * 0.01).toFixed(2) }}
          </view>
        </view>
        <u-line color="#E3E4E6" v-if="orderInfo.adjustPrice > 0"></u-line>
        <view class="moneyView" v-if="orderInfo.adjustPrice > 0">
          <view class="moneyTitle">
            <view>调价</view>
          </view>
          <view class="moneyText" style="color: orangered"
            >¥{{ (orderInfo.adjustPrice * 0.01).toFixed(2) }}
          </view>
        </view>
        <u-line color="#E3E4E6" v-if="orderInfo.discountPrice > 0"></u-line>
        <view class="moneyView" v-if="orderInfo.discountPrice > 0">
          <view class="moneyTitle">
            <view>优惠金额</view>
          </view>
          <view class="moneyText" style="color: orangered"
            >¥{{ (orderInfo.discountPrice * 0.01).toFixed(2) }}
          </view>
        </view>
        <u-line color="#E3E4E6"></u-line>
        <view class="allPriceView">
          <view class="moneyTitle">
            <view>{{ orderInfo.payStatus ? '实付' : '应付' }}</view>
          </view>
          <text class="allPrice" style="color: red"
            >¥{{ (orderInfo.payPrice * 0.01).toFixed(2) }}
          </text>
        </view>
      </view>
      <view class="layoutView" v-if="orderInfo.riderStaff || orderInfo.riderPicUrls">
        <view class="orderTitle dis-flex flex-x-baseline">
          <text>配送员信息</text>
          <view class="flex-1"></view>
          <view
            style="color: #10a28f; font-size: 26rpx"
            @click.stop.prevent="onCallPhone(orderInfo.riderStaff.contactMobile)"
          >
            联系TA
          </view>
        </view>
        <view class="orderText"
          >姓名：{{ orderInfo.riderStaff ? orderInfo.riderStaff.contactName : '无' }}</view
        >
        <view class="orderText"
          >手机号：{{ orderInfo.riderStaff ? orderInfo.riderStaff.contactMobile : '无' }}</view
        >
        <view class="orderText" v-if="orderInfo.riderRemark"
          >备注：{{ orderInfo.riderRemark }}
        </view>
        <view class="orderText" v-if="orderInfo.riderPicUrls && orderInfo.riderPicUrls.length > 0"
          >凭证图片：
        </view>
        <view
          class="orderText"
          v-if="orderInfo.riderPicUrls && orderInfo.riderPicUrls.length > 0"
          style="display: flex; flex-wrap: wrap"
        >
          <u-image
            class="picBox"
            border-radius="10"
            v-for="img in orderInfo.riderPicUrls"
            :src="img"
            :key="img"
            width="150rpx"
            height="150rpx"
          ></u-image>
        </view>
      </view>
      <view class="layoutView" v-if="orderInfo.combinationRecord">
        <view class="orderTitle">拼团信息</view>
        <view class="orderText">记录编号：{{ orderInfo.combinationRecordId }}</view>
      </view>
      <view class="layoutView" v-if="orderInfo.grouponPackage">
        <view class="orderTitle">团购信息</view>
        <view class="orderText">套餐编号：{{ orderInfo.grouponPackageId }}</view>
      </view>
      <view class="layoutView" v-if="orderInfo">
        <view class="orderTitle">订单信息</view>
        <view class="orderText">交易单号：{{ orderInfo.no }}</view>
        <view class="orderText" v-if="orderInfo.deliveryType == 1">配送类型：快递发货</view>
        <view class="orderText" v-if="orderInfo.deliveryType == 2">配送类型：到店自提</view>
        <view class="orderText" v-if="orderInfo.deliveryType == 3">配送类型：同城配送</view>
        <view class="orderText" v-if="orderInfo.deliveryType == 4"
          >{{
            orderInfo.shop.categoryCode === 'food' ? '配送类型：到店自取' : '配送类型：现场核销'
          }}
        </view>
        <view class="orderText"
          >创建时间：{{ $u.timeFormat(orderInfo.createTime, 'yyyy年mm月dd日 hh时MM分') }}
        </view>
        <view class="orderText" v-if="orderInfo.payStatus"
          >付款时间：{{ $u.timeFormat(orderInfo.payTime, 'yyyy年mm月dd日 hh时MM分') }}
        </view>
        <view class="orderText" v-if="orderInfo.userRemark"
          >订单备注：{{ orderInfo.userRemark }}
        </view>
        <view class="orderText" v-if="orderInfo.acceptedTime"
          >接单时间：{{ $u.timeFormat(orderInfo.acceptedTime, 'yyyy年mm月dd日 hh时MM分') }}
        </view>
        <view class="orderText" v-if="orderInfo.assignedTime"
          >派单时间：{{ $u.timeFormat(orderInfo.assignedTime, 'yyyy年mm月dd日 hh时MM分') }}
        </view>
        <view class="orderText" v-if="orderInfo.packedTime"
          >出餐时间：{{ $u.timeFormat(orderInfo.packedTime, 'yyyy年mm月dd日 hh时MM分') }}
        </view>
        <view class="orderText" v-if="orderInfo.deliveryTime"
          >{{ orderInfo.deliveryType === 1 ? '发货时间' : '配送时间' }}：{{
            $u.timeFormat(orderInfo.deliveryTime, 'yyyy年mm月dd日 hh时MM分')
          }}
        </view>
        <view class="orderText" v-if="orderInfo.logisticsName">
          物流公司：{{ orderInfo.logisticsName }}
        </view>
        <view class="orderText" v-if="orderInfo.logisticsNo">
          <view style="flex: 1">物流单号：{{ orderInfo.logisticsNo }}</view>
          <view @click="onCopy(orderInfo.logisticsNo)">复制</view>
        </view>
        <view class="orderText" v-if="orderInfo.receiveTime"
          >{{ orderInfo.deliveryType === 1 ? '收货时间' : '送达时间' }}：{{
            $u.timeFormat(orderInfo.receiveTime, 'yyyy年mm月dd日 hh时MM分')
          }}
        </view>
        <view class="orderText" v-if="orderInfo.finishTime"
          >完成时间：{{ $u.timeFormat(orderInfo.finishTime, 'yyyy年mm月dd日 hh时MM分') }}
        </view>
        <view class="orderText" v-if="orderInfo.cancelTime"
          >关闭时间：{{ $u.timeFormat(orderInfo.cancelTime, 'yyyy年mm月dd日 hh时MM分') }}
        </view>
        <view
          class="orderText"
          v-if="(orderInfo.type === 10 || orderInfo.type === 20) && orderInfo.dinePeoples"
          >用餐人数：{{ orderInfo.dinePeoples }}人
        </view>
        <view class="orderText" v-if="orderInfo.reserveDate"
          >预约时间：{{ $u.timeFormat(orderInfo.reserveDate, 'yyyy年mm月dd日') }}
          {{ orderInfo.reservePeriod }}
        </view>
      </view>
      <u-gap height="200"></u-gap>
    </scroll-view>
    <view v-if="orderInfo" class="footer-box">
      <view class="bottomView">
        <text class="hollow-btn btn" @click="$utils.goToUserCenter()">个人中心</text>
        <view
          class="btn-group"
          v-if="
            orderInfo.status == 10 && orderInfo.deliveryType == 1 && orderInfo.refundStatus === 0
          "
        >
          <view class="solid-btn btn" @click.stop.prevent="onDeliver(orderInfo)"> 立即发货 </view>
        </view>
        <view
          class="btn-group"
          v-else-if="
            (orderInfo.status == 10 || orderInfo.status == 20) &&
            orderInfo.deliveryType == 3 &&
            orderInfo.refundStatus === 0
          "
        >
          <view
            v-if="orderInfo.dineStatus == 10"
            class="solid-btn btn"
            @click.stop.prevent="onMealsAccepted(orderInfo)"
          >
            确认接单</view
          >
          <view
            v-else-if="orderInfo.dineStatus == 20 || orderInfo.dineStatus == 22"
            class="solid-btn btn"
            @click.stop.prevent="onMealsPacked(orderInfo)"
          >
            确认出餐</view
          >
        </view>
        <text
          class="hollow-btn btn"
          @click="onExpress"
          v-if="orderInfo.status == 10 && orderInfo.deliveryType == 1"
          >查看物流
        </text>
        <text
          class="solid-btn btn"
          @click="toClerk"
          v-if="
            orderInfo.status == 20 && orderInfo.deliveryType == 4 && orderInfo.refundStatus === 0
          "
          >去核销
        </text>
      </view>
    </view>

    <u-popup
      :closeable="true"
      width="550rpx"
      v-model="expressPopup"
      mode="bottom"
      height="auto"
      border-rad
      border-radius="15"
    >
      <view class="popup-box">
        <view class="popup-title"> 订单发货</view>
        <view style="margin-top: 40rpx" @click="expressPicker = true">
          <u-input
            @click="expressPicker = true"
            :readonly="true"
            :clearable="true"
            style="background-color: #efefef; padding: 10rpx 20rpx"
            v-model="form1.logisticsName"
            placeholder="请选择快递公司"
          ></u-input>
        </view>
        <view style="margin-top: 20rpx">
          <u-input
            style="background-color: #efefef; padding: 10rpx 20rpx"
            v-model="form1.logisticsNo"
            placeholder="请输入快递单号"
            :clearable="true"
          ></u-input>
        </view>
        <view class="" style="margin-bottom: 100rpx"></view>
        <view class="fixed-wapper1">
          <view class="submit-btn" @click="pushDeliver"> 确认发货</view>
        </view>
      </view>
    </u-popup>

    <u-picker
      v-model="expressPicker"
      mode="selector"
      @confirm="comfirmExpress"
      :range="exprees"
      range-key="name"
      range-value="id"
    ></u-picker>
  </view>
</template>

<script>
export default {
  data() {
    return {
      orderId: '',
      orderInfo: null,
      goodsList: [],
      form1: {
        id: null,
        logisticsId: '',
        logisticsName: '',
        logisticsNo: ''
      },
      expressPopup: false,
      expressPicker: false,
      exprees: []
    }
  },
  onLoad(res) {
    this.orderId = res.id ? res.id : ''
  },
  onShow() {
    this.initData()
  },
  computed: {
    payCountDownSeconds() {
      if (this.orderInfo && !this.orderInfo.payStatus) {
        return (this.orderInfo.payExpireTime - new Date().getTime()) / 1000
      }
      return 0
    },
    priceTotal: function () {
      let price = 0
      this.goodsList.forEach((item) => {
        price += item.price * item.count
      })
      return price
    }
  },
  methods: {
    formatCode(code) {
      return code
        .replace(/\s/g, '')
        .replace(/[^\d]/g, '')
        .replace(/(\d{3})(?=\d)/g, '$1 ')
    },
    initData() {
      let self = this
      self.$u.get('/app-api/trade/order/get-detail-seller?id=' + self.orderId).then((res) => {
        if (res.code !== 0) {
          self.$u.toast(res.msg)
          return
        }
        self.orderInfo = res.data
        self.goodsList = res.data.items
      })
    },
    onLocation(lat, lng) {
      uni.openLocation({
        latitude: Number(lat),
        latitude: Number(lng),
        success() {}
      })
    },
    onCallPhone(phone) {
      // #ifdef H5
      this.onCopy(phone)
      // #endif
      // #ifndef H5
      uni.makePhoneCall({
        phoneNumber: phone,
        fail(res) {
          uni.$u.toast(JSON.stringify(res))
        }
      })
      // #endif
    },
    onCopy(number) {
      let self = this
      uni.setClipboardData({
        data: number,
        success: function () {
          self.$u.toast('复制成功')
        }
      })
    },
    onMealsAccepted(item) {
      uni.showModal({
        title: '接单提示',
        content: `确定接受该外卖订单吗？`,
        success: (res) => {
          if (res.confirm) {
            this.performMealsAccepted(item)
          }
        }
      })
    },
    performMealsAccepted(item) {
      uni.showLoading()
      const self = this
      self.$u
        .post('/app-api/trade/order/accept?id=' + item.id)
        .then((res) => {
          uni.hideLoading()
          if (res.code === 0) {
            self.initData()
          } else {
            self.$u.toast(res.msg)
          }
        })
        .catch(() => {
          uni.hideLoading()
        })
    },
    onMealsPacked(item) {
      uni.showModal({
        title: '出餐提示',
        content: `请对照订单检查，确定已打包好了吗？`,
        success: (res) => {
          if (res.confirm) {
            this.performMealsPacked(item)
          }
        }
      })
    },
    performMealsPacked(item) {
      uni.showLoading()
      const self = this
      self.$u
        .post('/app-api/trade/order/pack?id=' + item.id)
        .then((res) => {
          uni.hideLoading()
          if (res.code === 0) {
            self.initData()
          } else {
            self.$u.toast(res.msg)
          }
        })
        .catch(() => {
          uni.hideLoading()
        })
    },
    onDeliver(item) {
      this.form1.id = item.id
      this.expressPopup = true
    },
    comfirmExpress(res) {
      let exp = this.exprees[res[0]]
      this.form1.logisticsName = exp.name
      this.form1.logisticsId = exp.id
    },
    pushDeliver() {
      let self = this
      if (!self.form1.logisticsId) {
        self.$u.toast('请选择快递公司')
        return
      }
      if (!self.form1.logisticsNo) {
        self.$u.toast('请输入快递单号')
        return
      }
      uni.showLoading()
      self.$u
        .post('/app-api/trade/order/delivery', self.form1)
        .then((res) => {
          uni.hideLoading()
          if (res.code === 0) {
            self.form1.id = null
            self.form1.logisticsId = ''
            self.form1.logisticsName = ''
            self.form1.logisticsNo = ''
            self.$u.toast('发货成功')
            self.initData()
            setTimeout(function () {
              self.expressPopup = false
            }, 800)
          } else {
            self.$u.toast(res.msg)
          }
        })
        .catch(() => {
          uni.hideLoading()
        })
    },
    toClerk() {
      this.$utils.route('/store/scan')
    },
    onExpress() {
      uni.navigateTo({
        url:
          '/other/express-process/express-process?id=' +
          this.orderInfo.id +
          '&goodsJson=' +
          JSON.stringify(this.orderInfo.items[0])
      })
    }
  }
}
</script>

<style scoped lang="scss">
@import url('@/style/btn.css');
@import url('./order-details.css');

page {
  background: #f2f2f2;
}

.submit-btn {
  width: 94%;
}

.right {
  width: 150rpx;
  height: 60rpx;
  border-radius: 30rpx;
  border: 1px solid #e6e6e6;
  line-height: 60rpx;
  color: #666666;
  text-align: center;
}

.store-info {
  margin-bottom: 20rpx;

  .store-left {
    font-size: 30rpx;

    .store-add {
      font-size: 24rpx;
      color: #666666;
    }
  }
}

.order-code {
  font-weight: 600;
  font-size: 36rpx;
  color: #333333;
}

.slot-btn {
  width: 200rpx;
  height: 200rpx;
  background: #f5f5f5;
  border-radius: 20rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-flow: column;
}
</style>
